import { useState, useRef, useEffect, useCallback } from 'react';
import {
  Image,
  Toast,
  List,
} from 'antd-mobile';
import { udp, useAllReady, useAsyncEffect } from '@cscec/udp-mobile-ui';
import { useSpeechRecognition } from '@/util';
import { Col, Row, Card, Button, Space, } from 'antd';
import { AudioOutlined, PlayCircleOutlined, SoundOutlined } from '@ant-design/icons';
import { Uphistory } from '@/pages/Schme/service';
import { queryDetail } from './service';
import CardHeader from '../CardHeader';
import './index.less';
import { useAudioPlay } from '@/hooks/useAudioPlay';

const Recording = ({ values, num, length, setNum }: any) => {
  const [isRecording, setIsRecording] = useState(false);
  const [audioURL, setAudioURL] = useState<string | null>(null);
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const audioChunksRef = useRef<Blob[]>([]);
  const [mess, setMess] = useState<any>([]);
  const [reindex, setReindex] = useState<any>(0)
  const [cardValue, setCardValue] = useState('1');
  const [cardList, setCardList] = useState<any>([]);
   const { isPlaying, isLoading, playAudio, stopAudio } = useAudioPlay({});

  const totalSentences = cardList.length;


  useEffect(() => {
    if (values.tbSentencesVos && values.tbSentencesVos.length > 0) {
      setMess(values.tbSentencesVos)
    }
    // newCardList.push(cardList[0])

  }, [values])

  useAsyncEffect(async () => {
    if (mess.length && mess.length > 0) {
      console.log('num', num);
      const result = await queryDetail({ masterId: mess[Number(num)].masterId, cardNo: num })
      setCardList(result)
    }
  }, [cardValue, mess])

  const handleRecognitionResult = useCallback((text: string) => {
    console.log(text)
    const ttstr = udp.deepCopy(mess)
    console.log(reindex)
    ttstr[reindex].userSpeech = text,
      setMess(ttstr)
  }, [reindex, mess]);

  const { isListening, startListening, stopListening } = useSpeechRecognition(handleRecognitionResult);

  // 开始录音
  const startRecording = async (index) => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      mediaRecorderRef.current = new MediaRecorder(stream);
      audioChunksRef.current = [];

      mediaRecorderRef.current.ondataavailable = (event) => {
        audioChunksRef.current.push(event.data);
      };
      console.log(index)
      setReindex(index)

      mediaRecorderRef.current.onstop = () => {
        const audioBlob = new Blob(audioChunksRef.current, { type: 'audio/wav' });
        const url = URL.createObjectURL(audioBlob);
        setAudioURL(url);
      };

      mediaRecorderRef.current.start();
      startListening();
      setIsRecording(true);
      Toast.show({ content: '录音开始', position: 'bottom' });
    } catch (error) {
      console.error('无法访问麦克风:', error);
      Toast.show({ content: '无法访问麦克风，请检查权限设置', position: 'bottom' });
    }
  };

  // 停止录音
  const stopRecording = () => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop();
      mediaRecorderRef.current.stream.getTracks().forEach(track => track.stop());
      stopListening()
      setIsRecording(false);
      Toast.show({ content: '录音结束', position: 'bottom' });
    }
  };

  // 播放录音
  const playRecording = () => {
    if (audioURL) {
      const audio = new Audio(audioURL);
      audio.play();
    } else {
      Toast.show({ content: '没有可播放的录音', position: 'bottom' });
    }
  };

  //翻页功能
  const next = () => {
    if (num + 1 > length) {
      Uphistory({
        textbookId: values.textbookId,
        unitId: values.unitId,
        topicId: values.topicId,
        exerciseId:values.id,
        completionStatus: 2, studyFlag: 1
      }).then((rt) => {
        udp.message('当前主题已经学习完毕!')
        udp.close()
      })
    } else {
      setNum(num + 1)
    }
  }

  const [cardCount, setCardCount] = useState(1);

  // 增加卡片数量的函数
  const increaseCards = () => {
    if (cardCount >= cardList.length) {
      getCardValue(cardCount + 1)
    } else {
      setCardCount(prevCount => prevCount + 1);
      console.log('cardCount', cardCount);
      console.log('cardCount', cardList.length);
    }
  };

  const getCardValue = (data) => {
    console.log('data', data);
    setCardValue(data);
  };





  return (
    <>
      {/* <CardHeader title1="卡片" title2="句子" values={values} cardValue={getCardValue} ></CardHeader>
       */}

      {Array.from({ length: cardCount }, (_, index) => (
        <Card className="title-card">
          <p className='sentense'>{cardList[index]?.name}</p>
          <div className="phrase-controls">
            <Space size="middle">
              <Button
                type="default"
                shape="circle"
                icon={<SoundOutlined style={{ color: "#a7acef" }} />}
                className="control-button"
                onClick={() => {
                  playAudio(cardList[index]?.name)
                }}
              />
              <Button
                type="default"
                shape="circle"
                icon={<AudioOutlined style={{ color: "#a7acef" }} />}
                className="control-button"
                onClick={isRecording ? stopRecording : () => {
                  startRecording(index)
                }}
                disabled={!navigator.mediaDevices}

              />
              <Button
                type="default"
                shape="circle"
                icon={<PlayCircleOutlined style={{ color: "#a7acef" }} />}
                className="control-button"
                onClick={playRecording}
              />
            </Space>
          </div>
        </Card>
      ))}
      {/* 按钮信息 */}
      <div className="button-container">
        <Button className={`${cardCount >= totalSentences}` ? "card-button-disable" : "card-button"}
          block shape='round' style={{
            "width": "90%",
            "height": "3rem",
            "fontSize": "18px",
            "fontWeight": "700",
            "backgroundColor": "#a7acef",
            // "backgroundColor": `${cardCount >= cardList.length}` ? "#2029a9ff" : "#a7acef",
            "color": "#ffffff"
          }}
          onClick={increaseCards}>继续</Button>
      </div>

    </>
  );
};

export default Recording;